<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\service\Common;
use app\common\service\ZipFile;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use app\admin\library\Auth;
use Exception;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\exception\PDOException;
use think\Db;
use think\exception\ValidateException;

/**
 * 充电桩管理
 *
 * @icon fa fa-circle-o
 */
class ChargePile extends Backend
{
    
    /**
     * ChargePile模型对象
     * @var \app\admin\model\ChargePile
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\ChargePile;
        $this->view->assign("statusList", $this->model->getStatusList());
    }


    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 2; $currentRow <= 2; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 3; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }
                if ($row) {
                    $insert[] = $row;
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }

        $manufacturer_list=\app\admin\model\Manufacturer::where('status',1)->column('id','name');
        $kind_list=\app\admin\model\Kind::where('status',1)->column('id','kind_name');
        $operator_list=\app\admin\model\Operator::where('status',1)->column('id','operator_name');
        $operator_code=\app\admin\model\Operator::where('status',1)->column('operator_code','id');


        foreach ($insert as $k=>&$v){
            if (empty($v['operator_code'])||empty($v['operator_id'])||empty($v['manufacturer_id'])||
                empty($v['device_number'])||empty($v['kind_id'])||empty($v['province'])||empty($v['citys'])||
                empty($v['area'])||empty($v['street'])||empty($v['community'])||empty($v['village'])||
                empty($v['address'])||empty($v['longitude'])||empty($v['latitude'])||empty($v['port'])||
                empty($v['installtime'])||empty($v['meter_code'])){
                $this->error('有必填项未填写');
            }
            if (array_key_exists($v['manufacturer_id'],$manufacturer_list)){
                $v['manufacturer_id']=$manufacturer_list[$v['manufacturer_id']];
            }else{
                $this->error('导入的品牌不存在，请修改后导入');
            }
            if (array_key_exists($v['kind_id'],$kind_list)){
                $v['kind_id']=$kind_list[$v['kind_id']];
            }else{
                $this->error('导入的种类不存在，请修改后导入');
            }
            if (array_key_exists($v['operator_id'],$operator_list)){
                $v['operator_id']=$operator_list[$v['operator_id']];
                $v['operator_code']=$operator_code[$v['operator_id']];
            }else{
                $this->error('导入的运营商不存在，请修改后导入');
            }
            $v['city']=$v['province'].'/'.$v['citys'].'/'.$v['area'];
            $v['installtime']=strtotime(gmdate('Y-m-d',($v['installtime']-25569)*24 * 60 * 60));

        }


        if (!$insert) {
            $this->error(__('No rows were updated'));
        }


        try {
            //是否包含admin_id字段
            $has_admin_id = false;
            foreach ($fieldArr as $name => $key) {
                if ($key == 'admin_id') {
                    $has_admin_id = true;
                    break;
                }
            }
            if ($has_admin_id) {
                $auth = Auth::instance();
                foreach ($insert as &$val) {
                    if (!isset($val['admin_id']) || empty($val['admin_id'])) {
                        $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
                    }
                }
            }
            $this->model->saveAll($insert);
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['manufacturer','operator','kind','user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('manufacturer')->visible(['name']);
				$row->getRelation('operator')->visible(['operator_name']);
				$row->getRelation('kind')->visible(['kind_name']);
				$row->getRelation('user')->visible(['nickname']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $citys=explode('/',$params['city']);
                $params['province']=$citys[0];
                $params['citys']=$citys[1];
                $params['area']=$citys[2];
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {

        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $citys=explode('/',$params['city']);
                $params['province']=$citys[0];
                $params['citys']=$citys[1];
                $params['area']=$citys[2];

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    
                    $arr=[
                        "device_number"=>$params['device_number'],
                        "device_name"=>$params['device_number'],
                        "area"=>$params['area'],
                        "street"=>$params['street'],
                        "community"=>$params['community'],
                        "village"=>$params['village'],
                        "address"=>$params['address'],
                        "longitude"=>$params['longitude'],
                        "latitude"=>$params['latitude'],
                        "unity_type"=>$params['unit_type'],
                        "powers"=>$params['powers'],
                        "status"=>$params['status'],
                    ];

                    /*$addurl='http://113.108.32.36:8093/iap/api/v1/notify/deviceData';
                    $adddata['requestId']=(new Common())->createToken($params['device_number']);
                    $adddata['notifyType']='deviceData';
                    $adddata['serviceType']='dataReport';
                    $adddata['deviceId']=$params['device_number'];
                    $adddata['data']=$arr;
                    $addjsonStr = json_encode($adddata,JSON_UNESCAPED_UNICODE);  //设置了Content-Type: application/json，传参要转化为JSON，否则后台接收不到数据
                    $addheaders=array("Content-Type: application/json", "Content-Length: " . strlen($addjsonStr) . "","Accept: application/json");
                    $addres=(new Common())->CurlRequest($addurl,$addjsonStr,$addheaders);
                    $addres1=json_decode($addres,true);
                    file_put_contents('deviceData',print_r($addres1,true));
                    
                    file_put_contents('deviceData11',print_r($addjsonStr,true));

                    $url='http://113.108.32.36:8093/iap/api/v1/notify/deviceStatus';
                    $data['requestId']=(new Common())->createToken($params['device_number']);
                    $data['notifyType']='deviceStatus';
                    $data['deviceId']=$params['device_number'];
                    $data['status']=$params['status']==1?'online':'offline';
                    $jsonStr = json_encode($data,JSON_UNESCAPED_UNICODE);  //设置了Content-Type: application/json，传参要转化为JSON，否则后台接收不到数据
                    $headers=array("Content-Type: application/json", "Content-Length: " . strlen($jsonStr) . "","Accept: application/json");
                    $res=(new Common())->CurlRequest($url,$jsonStr,$headers);
                    $res1=json_decode($res,true);
                    // file_put_contents('111',print_r($jsonStr,true));
                    file_put_contents('deviceStatus',print_r($res1,true));*/
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }


            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function out()
    {

//        $arr=['平湖街道'=>440307003000,'坪地街道'=>440307006000,'南湾街道'=>440307012000,'坂田街道'=>440307013000,'布吉街道'=>440307014000,
//            '龙城街道'=>440307015000,'龙岗街道'=>440307016000,'横岗街道'=>440307017000,'宝龙街道'=>440307019003,'园山街道'=>440307020006,
//            '吉华街道'=>440307018005
//        ];
//        $list=$this->model->where('status',1)->where('community','龙岭社区')->field('device_number,longitude,latitude,province,citys,area,street,community,village,address')->select();
        $spreadsheet=new Spreadsheet();
        $sheet=$spreadsheet->getActiveSheet();

//        $sheet->getCell('A1')->setValue('设备编码');
//        $sheet->getCell('B1')->setValue('设备名称');
//        $sheet->getCell('C1')->setValue('经度（数字类型，东经为正，西经为负）');
//        $sheet->getCell('D1')->setValue('纬度（数字类型，北纬为正，南纬为负）');
//        $sheet->getCell('E1')->setValue('街道邮编');
//        $sheet->getCell('F1')->setValue('位置');
//        $i=2;
//        foreach ($list as $v){
//
//            $sheet->getCell('A'.$i)->setValue($v['device_number']);
//            $sheet->getCell('B'.$i)->setValue($v['device_number']);
//            $sheet->getCell('C'.$i)->setValue($v['longitude']);
//            $sheet->getCell('D'.$i)->setValue($v['latitude']);
//            $sheet->getCell('E'.$i)->setValue(array_key_exists($v['street'],$arr)?$arr[$v['street']]:'');
//            $sheet->getCell('F'.$i)->setValue($v['province'].'-'.$v['citys'].'-'.$v['area'].'-'.$v['street'].'-'.$v['community']);
//                $i++;
//        }

        $sheet->getCell('A2')->setValue('运营商编码');
        $sheet->getCell('B2')->setValue('运营商');
        $sheet->getCell('C2')->setValue('品牌');
        $sheet->getCell('D2')->setValue('设备号');
        $sheet->getCell('E2')->setValue('种类');
        $sheet->getCell('F2')->setValue('省');
        $sheet->getCell('G2')->setValue('市');
        $sheet->getCell('H2')->setValue('区');
        $sheet->getCell('I2')->setValue('街道');
        $sheet->getCell('J2')->setValue('社区');
        $sheet->getCell('K2')->setValue('村庄');
        $sheet->getCell('L2')->setValue('位置');
        $sheet->getCell('M2')->setValue('经度');
        $sheet->getCell('N2')->setValue('纬度');
        $sheet->getCell('O2')->setValue('端口数量');
        $sheet->getCell('P2')->setValue('安装日期');
        $sheet->getCell('Q2')->setValue('电表编码');
        $sheet->getCell('R2')->setValue('设备型号');
        $sheet->getCell('S2')->setValue('功率');
        $sheet->getCell('T2')->setValue('安装方式');
        $sheet->getCell('U2')->setValue('充电方式');
        $title = '充电桩导入模板';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $title . '.xlsx"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $objWriter = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $objWriter->save('php://output');
        return;
    }


    public function img()
    {

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $user_data =  Db::name('user')->where(['nickname'=>$params['user_name']])->field("id")->find();
                if(!$user_data){
                    $this->error(__('所属师傅不存在', '/charge_pile?ref=addtabs'));
                    exit;
                }
                $endtime = strtotime($params['endtime']);
                $strtime = strtotime($params['strtime']);
                if($strtime >= $endtime){
                    $this->error(__('结束时间必须大于开始时间', '/charge_pile?ref=addtabs'));
                    exit;
                }
                if(($endtime-$strtime)>5184000){
                    $this->error(__('选择时间不能超过60天', '/charge_pile?ref=addtabs'));
                    exit;
                }

                // $today = strtotime(date("Y-m-d"),time());
                // $end = $today+60*60*24;
                $list=Db::table('yp_charge_pile')->alias('cp')
                ->join('manufacturer m','cp.manufacturer_id=m.id','left')
                ->join('user u','cp.user_id=u.id','left')
                ->where('cp.status = 1 and cp.createtime>='.$strtime.' and cp.createtime<='.$endtime);
                // ->where('cp.createtime','between',[$today,$end])
                if (!empty($params['user_name'])) $list=$list->where('u.nickname','like',"%".$params['user_name']."%");
                $list=$list
                ->field('cp.device_number,cp.images,m.name manufacturer_name,u.nickname')
                ->select();
                
                $config = get_addon_config('alioss');
                
                $imglist=[];
                foreach ($list as $k=>&$v){
                    if(strlen($v['images'])!=0){
                        $images=explode(',',$v['images']);
                        $j=1;
                        for ($i=0;$i<count($images);$i++){
                            $path=parse_url($images[$i]);
                            $arr=[
                                'image_src'=>$config['cdnurl'].$path['path'].'?x-oss-process=image/resize,p_10',
                                'image_name'=>$v['device_number'].'-'.$v['manufacturer_name'].'-'.$v['nickname'].'/'.$v['device_number'].'-'.$v['manufacturer_name'].'-'.$j.'.jpg'
                            ];
                            $j++;
                            $imglist[]=$arr;
                        }

                    }
                }
                //下面是实例操作过程：
                $dfile = tempnam('/tmp', 'tmp');//产生一个临时文件，用于缓存下载文件
                $zip = new ZipFile();
        //----------------------
                $filename = '充电桩图片.zip'; //下载的默认文件名

        //以下是需要下载的图片数组信息，将需要下载的图片信息转化为类似即可

                foreach($imglist as $v){
                    $zip->add_file(file_get_contents($v['image_src']), iconv('utf-8','gbk',$v['image_name']));
                    // 添加打包的图片，第一个参数是图片内容，第二个参数是压缩包里面的显示的名称, 可包含路径
                    // 或是想打包整个目录 用 $zip->add_path($image_path);
                }
        //----------------------
                $zip->output($dfile);

        // 下载文件
                ob_clean();
                header('Pragma: public');
                header('Last-Modified:'.gmdate('D, d M Y H:i:s') . 'GMT');
                header('Cache-Control:no-store, no-cache, must-revalidate');
                header('Cache-Control:pre-check=0, post-check=0, max-age=0');
                header('Content-Transfer-Encoding:binary');
                header('Content-Encoding:none');
                header('Content-type:multipart/form-data');
                header('Content-Disposition:attachment; filename="'.$filename.'"'); //设置下载的默认文件名
                header('Content-length:'. filesize($dfile));
                $fp = fopen($dfile, 'r');
                while(connection_status() == 0 && $buf = @fread($fp, 8192)){
                    echo $buf;
                }
                fclose($fp);
                @unlink($dfile);
                @flush();
                @ob_flush();
                exit();
                $this->success('成功','/rfDnxZXcKM.php/charge_pile?ref=addtabs');
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();

    }
    
    public function ceshi($ids)
    {
        if ($this->request->isAjax()) {
             $list=Db::table('yp_charge_pile')->alias('cp')
                ->join('manufacturer m','cp.manufacturer_id=m.id','left')
                ->join('user u','cp.user_id=u.id','left')
                ->where('cp.status',1)
                ->where('cp.id',$ids)
                ->field('cp.device_number,cp.images,m.name manufacturer_name,u.nickname')
                ->find();
                
                $config = get_addon_config('alioss');
                
                $imglist=[];
 
                    if(strlen($list['images'])!=0){
                        $images=explode(',',$list['images']);
                        $j=1;
                        for ($i=0;$i<count($images);$i++){
                            $path=parse_url($images[$i]);
                            $arr=[
                                'image_src'=>$config['cdnurl'].$path['path'].'?x-oss-process=image/resize,p_10',
                                'image_name'=>$list['device_number'].'-'.$list['manufacturer_name'].'-'.$list['nickname'].'/'.$list['device_number'].'-'.$list['manufacturer_name'].'-'.$j.'.jpg'
                            ];
                            $j++;
                            $imglist[]=$arr;
                        }

                    }
                
                //下面是实例操作过程：
                $dfile = tempnam('/tmp', 'tmp');//产生一个临时文件，用于缓存下载文件
                $zip = new ZipFile();
        //----------------------
                $filename = $list['device_number'].'.zip'; //下载的默认文件名

        //以下是需要下载的图片数组信息，将需要下载的图片信息转化为类似即可

                foreach($imglist as $v){
                    $zip->add_file(file_get_contents($v['image_src']), iconv('utf-8','gbk',$v['image_name']));
                    // 添加打包的图片，第一个参数是图片内容，第二个参数是压缩包里面的显示的名称, 可包含路径
                    // 或是想打包整个目录 用 $zip->add_path($image_path);
                }
        //----------------------
                $zip->output($dfile);

        // 下载文件
                ob_clean();
                header('Pragma: public');
                header('Last-Modified:'.gmdate('D, d M Y H:i:s') . 'GMT');
                header('Cache-Control:no-store, no-cache, must-revalidate');
                header('Cache-Control:pre-check=0, post-check=0, max-age=0');
                header('Content-Transfer-Encoding:binary');
                header('Content-Encoding:none');
                header('Content-type:multipart/form-data');
                header('Content-Disposition:attachment; filename="'.$filename.'"'); //设置下载的默认文件名
                header('Content-length:'. filesize($dfile));
                $fp = fopen($dfile, 'r');
                while(connection_status() == 0 && $buf = @fread($fp, 8192)){
                    echo $buf;
                }
                fclose($fp);
                @unlink($dfile);
                @flush();
                @ob_flush();
                exit();
        }
        
    }
}
